package com.cpp.server.websocket;

import com.cpp.server.context.UserHolder;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class MyWebSocketHandler extends TextWebSocketHandler {

    // 存储 userId 到 WebSocketSession 的映射
    private static final Map<String, WebSocketSession> userSessions = new ConcurrentHashMap<>();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        String userId = String.valueOf(UserHolder.getCurrentUser().getId()); // 使用 UserHandler 获取 userId
        if (userId != null) {
            userSessions.put(userId, session);
            System.out.println("User connected: " + userId);
        } else {
            session.close(CloseStatus.POLICY_VIOLATION);
        }
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        String userId = String.valueOf(UserHolder.getCurrentUser().getId()); // 使用 UserHandler 获取 userId
        if (userId != null) {
            userSessions.remove(userId);
            System.out.println("User disconnected: " + userId);
        }
    }

    // 给指定用户发送消息
    public static void sendMessageToUser(String message) {
        String userId = String.valueOf(UserHolder.getCurrentUser().getId()); // 使用 UserHandler 获取 userId
        WebSocketSession session = userSessions.get(userId);
        if (session != null && session.isOpen()) {
            try {
                session.sendMessage(new TextMessage(message));
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            System.out.println("User not found or session closed: " + userId);
        }
    }
}